package com.zwx.algorithms.pub.util;

import org.slf4j.Logger;
import org.slf4j.event.Level;

/**
 * 在java运行时修改log level，主要支持java本身测试方便。web应用还是使用log的配置文件。 当前支持的是slf4j+logback
 */
public class LogUtils {
  public static void resetLogLevel(Logger log, Level level) {
    if (log instanceof ch.qos.logback.classic.Logger) {
      ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) log;
      String originalLevel = logger.getLevel() == null ? null : logger.getLevel().levelStr;
      switch (level) {
        case DEBUG:
          logger.setLevel(ch.qos.logback.classic.Level.DEBUG);
          break;
        case INFO:
          logger.setLevel(ch.qos.logback.classic.Level.INFO);
          break;
        case ERROR:
          logger.setLevel(ch.qos.logback.classic.Level.ERROR);
          break;
        case WARN:
          logger.setLevel(ch.qos.logback.classic.Level.WARN);
          break;
        default:
          logger.setLevel(ch.qos.logback.classic.Level.INFO);

      }
      System.out.println("logger(" + log.getName() + ") reset loglevel from '" + originalLevel
          + "' to '" + logger.getLevel().levelStr + "'");
    }
  }
}
